package org.sunriz.utils;

public class GetName {
    public static String getLastName(String text) {
        // 如果输入文本为空，直接返回 null
        if (text == null || text.isEmpty()) {
            return null;
        }

        // 找到最后一个逗号的位置
        int lastCommaIndex = text.lastIndexOf(',');
        if (lastCommaIndex == -1) {
            return null; // 没有逗号
        }

        // 从逗号前一个位置开始向前查找
        int endIndex = lastCommaIndex - 1;
        int startIndex = endIndex;

        // 向前查找直到遇到指定字符或开头
        while (startIndex >= 0) {
            char c = text.charAt(startIndex);

            // 检查是否为终止字符：中文、括号、空格
            if (isChinese(c) || isClosingBracket(c) || Character.isWhitespace(c)|| c == ',') {
                // 跳过终止字符前的空白
//                while (startIndex + 1 <= endIndex && Character.isWhitespace(text.charAt(startIndex + 1))) {
//                    startIndex++;
//                }
                break;
            }

            startIndex--;
        }

        // 调整起始位置（跳过终止字符）
        startIndex++;

        // 提取子字符串
        if (startIndex <= endIndex && startIndex >= 0) {
            return text.substring(startIndex, endIndex + 1);
        }

        return null;
    }

    // 判断字符是否为中文
    private static boolean isChinese(char c) {
        Character.UnicodeBlock block = Character.UnicodeBlock.of(c);
        return block == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || block == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || block == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || block == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B
                || block == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION;
    }

    // 判断字符是否为结束括号或者\
    private static boolean isClosingBracket(char c) {
        return c == ')' || c == '）' || c == '\\';
    }
}
